<template>
	<om-addpage style="padding-top: 35px;" :busCode="busCode" :menuName="menuName" @formSubmit="formSubmit" :showHistoryBtn="true">
		<om-autoform ref="autoform" :initConfigData="mainConfigData" :initValue="initValue"></om-autoform>
		<om-sub :title="ms_title" :subTitle="ms_subtitle">
			<uni-list>
				<view v-for="(item, index) in workList" :key="index" >
					<uni-list-item 
						:avatar="index + 1"
						:showArrow="true"
						@click="openWork(index)" 
						:showClear="getClearFlag(index)"
						@iconClear="delSub(index)">
						<view>{{ item.itemName + (item.busRange? "("+ item.busRange +")":"")}}</view>
						<view class="text-gray text-sm padding-bottom-xs padding-top-xs">{{ item.targetValueName }}</view>
						<view class="text-gray text-sm padding-bottom-xs padding-top-xs">{{ getTip(item) }}</view>
					</uni-list-item>
				</view>
			</uni-list>
			<view class="tui-flex align-center justify-center padding-top">
				<text class="lg text-green cuIcon-add" @click="openWork()">{{ '增加' + ms_title }}</text>
			</view>
		</om-sub>
		<om-white-space bgColor="#eee"></om-white-space>
	</om-addpage>
</template>

<script>
import { getUrl,confirmModal,errorModal } from '@/static/js/common.js';
import { getFormFields,formValidation, tranferToEditors, changeEditor, configSelectData, hasValue,formShowLoading ,verifyDataList} from '@/static/js/formUtil.js';
import { mapState } from 'pinia';
import {useLoginUserStore} from '@/stores/login-user.js';
export default {
	provide() {
		return {
			formPage: this
		};
	},
	data() {
		return {
			menuName: '月指标计划',
			id: '',
			busCode: 'OBJ0503',
			formdata: {},
			mainConfigData: [],
			subConfigData: [],
			initValue: {
				objStr3: '',
				busCode: 'OBJ0503'
			},
			workCacheKey: 'obj-m-tinstmonthlytargetindex-work-cache',
			workConfigDataCacheKey: 'obj-m-tinstmonthlytargetindex-work-configdata-cache',
			userCacheKey:"obj-m-tinstmonthlytargetindex-user-cache",
			workList: [],
			defaultWorkList:[],//默认赋值的数据
			ms_title: '明细',
			ms_subtitle: '',
			scoreCode:"DD021017003",
			scoreNum:''
		};
	},
	computed: {
		...mapState(useLoginUserStore, ['userName', 'userId'])
	},
	methods: {
		formSubmit() {
			let _that = this;
			var checkRes = formValidation(this.$refs.autoform.configData, this.formdata);
			if (checkRes) {
				this.om.toast(checkRes);
			} else {
				var ret = verifyDataList(this.workList,this.subConfigData,this.ms_title)
				if (typeof(ret) == "string") {
					this.om.toast(ret);
					return;
				}
				_that.formdata.objStr1 = JSON.stringify(this.workList)
				_that.om.formSave('tinstMonthlyTargetIndex/addTinstMonthlyTargetIndex', _that.formdata, _that);
			}
		},
		getClearFlag(index) {
			if(hasValue(index)){
				if(this.defaultWorkList.length) {
					if(index >= this.defaultWorkList.length){
						return true
					} else {
						var item = this.workList[index]
						if(item.deleteInMonthProj) {
							return true
						} else {
							return false
						}
					}
				} else {
					return true
				}
			}else{
				return true
			}
		},
		getTip(item){
			var s = ''
			if(item.monthTargetCode){
				s += "月度目标值" + item.monthTargetCode
			}else{
				s += "月度目标值未填写"
			}
			if(item.lastYearSamePeriod){
				s += " | 上年同期" + item.lastYearSamePeriod
			}
			return s;
		},
		openWork(index) {
			var checkRes = formValidation(this.$refs.autoform.configData, this.formdata);
			if (checkRes) {
				this.om.toast(checkRes);
			} else {
				uni.setStorage({
					key: this.workConfigDataCacheKey,
					data: this.subConfigData
				});
				uni.setStorage({
					key: this.workCacheKey,
					data: this.workList
				});
				var param = {
					configDataCacheKey: this.workConfigDataCacheKey,
					cachename: this.workCacheKey,
					index: index,
					zposId:this.formdata.zposId,
					busCode:this.busCode,
					year:this.formdata.year,
					monthCode:this.formdata.monthCode,
					deleteFlag:this.getClearFlag(index)
				};
				if(hasValue(index)){
					var d = this.workList[index];
					param.prefix = d.logicRelationshipName;
					param.suffix = d.indexUnitName
				}
				var url = getUrl('data-info', param);
				uni.navigateTo({
					url: url
				});
			}
		},
		delSub(index){
			if(index != null) {
				this.workList.splice(index,1)
			}
		},
		onSelectZpos(item){
			let _that = this
			var pro1 = this.om.request('posBusiAuth/GW165', {
				posId:item.id,
				code:_that.busCode
			})
			var pro2 = this.om.request('tinstMonthlyTargetIndex/verifyZpos', {
				zposId:item.id
			})
			Promise.all([pro1, pro2]).then(res=>{
				if(res[0].succeed){
					if(res[0].value.tip){
						errorModal(_that, "提示信息", res[0].value.tip, function(){
							 _that.clearZpos()
						})
					}else{
						if(res[1].succeed){
							if(res[1].value){
								errorModal(_that, "提示信息", res[1].value, function(){
									 _that.clearZpos()
								})
							}
						}else{
							_that.om.toast(res[1].msg);
						}
					}
				} else {
					_that.om.toast(res[0].msg);
				}
			})
		},
		clearZpos(){
			this.$refs.autoform.clear('topinfo', 'zposId');
			this.$refs.autoform.clear('topinfo', 'year');
			this.$refs.autoform.changeEditor('topinfo', 'year', 'data',[])
			this.$refs.autoform.clear('topinfo', 'monthCode');
			this.$refs.autoform.changeEditor('topinfo', 'monthCode', 'data',[])
			this.workList = []
			this.defaultWorkList = []
		},
		onSelectYear(item){
			let _that = this
			this.om.request('tinstMonthlyTargetIndex/BD021_1', {
				year:item.value,
				busCode:this.busCode,
				zposId:this.formdata.zposId
			}).then(res=>{
				if(res.succeed && res.value){
					errorModal(_that, "提示信息", res.value, function(){
						 _that.clearYear()
						 
					})
				}else{
					_that.monthFunc(item);
				}
			})
		},
		clearYear(){
			this.$refs.autoform.clear('topinfo', 'year');
			this.$refs.autoform.clear('topinfo', 'monthCode');
			this.$refs.autoform.changeEditor('topinfo', 'monthCode', 'data',[])
			this.workList = []
			this.defaultWorkList = []
		},
		monthFunc(item) {
			let _that = this
			this.om.request('dictZero/getRecentMonth', {year:item.value}).then(res=>{
				//if(res instanceof Array){
				if(Object.prototype.toString.call(res)==='[object Array]'){
					_that.$refs.autoform.changeEditor("topinfo","monthCode","data",configSelectData(res, "code","dicname"))
				}
			})
		},
		onSelectMonth(item){
			let _that = this
			this.om.request('tinstMonthlyTargetIndex/BD021', {
				year:this.formdata.year,
				busCode:this.busCode,
				monthCode: item.value,
				zposId:this.formdata.zposId
			}).then(data=>{
				if (data.succeed && data.value) {
				    if (data.value.one) {
						errorModal(_that, "提示信息", data.value.one, function(){
							 _that.$refs.autoform.clear('topinfo', 'monthCode');
						})
					} else if (data.value.two) {
						confirmModal(_that, "提示信息", data.value.two, function(){
							 _that.getDataList()
						}, function(){
							_that.$refs.autoform.clear('topinfo', 'monthCode');
						})
					} else {
						_that.getDataList();
					}
				} else {
					_that.getDataList();
				}
			})
		},
		clearMonth(){
			this.$refs.autoform.clear('topinfo', 'monthCode');
			this.workList = []
			this.defaultWorkList = []
		},
		getDataList(){
			let _that = this
			this.om.request('tinstMonthlyTargetIndex/getDataList', {
				year:this.formdata.year,
				monthCode: this.formdata.monthCode,
				zposId:this.formdata.zposId
			}).then(data=>{
				if (data.succeed && data.value) {
				   for (var i = 0; i < data.value.length; i++) {
					   if (data.value[i].ratioName) {
						   data.value[i].yearRatio = data.value[i].ratioName;
					   }
				   }
				   _that.defaultWorkList = data.value
				   _that.workList = data.value
				} else {
					_that.om.toast(data.msg)
				}
			})
		},
		initLoad(options) {
			let _that = this;
			if (!this.busCode) {
				return;
			}
			//加载得分最大值
			_that.om.request('dataDict/getIntByCode',{code:_that.scoreCode}).then(res=>{
				if(res.succeed){
					 _that.scoreNum = res.value
				}
			})
			var pro1 = this.om.request('formFieldConfig/addPage', { code: this.busCode });
			var pro2 = this.om.request('wxPosBusiAuth/isnewList', { code: this.busCode }, 'post');
			var pro3 = ""
			var fileId = options.fileId
			if(fileId){
				pro3 = this.om.request(
					'tinstMonthlyTargetIndex/getInfo',
					{
						id:fileId
					},
					'post'
				)
			}
			//多个AJAX全部完成时开始执行
			Promise.all([pro1, pro2,pro3])
				.then(res => {
					if (res[0].succeed) {
						let data = res[0].value;
						var mainData = [
							{
								key: 'topinfo',
								editors: tranferToEditors(data.top)
							}
						];
						if (data.bodyTitle.length > 0) {
							for (var i = 0; i < data.bodyTitle.length; i++) {
								var datas = data['body' + i];
								_that.ms_title = data.bodyTitle[i].itemName;
								_that.subConfigData.push({
									title: data.bodyTitle[i].itemName,
									key: data.bodyTitle[i].fieldId,
									issub: true,
									editors: tranferToEditors(datas)
								});
							}
						}
						var date = new Date()
						var currentYear = date.getFullYear()
						changeEditor(mainData[0].editors,"year","data",[{text:"请选择"},{
								value:currentYear,
								text:currentYear
							},{
								value:currentYear+1,
								text:currentYear+1
							}],
						)
						changeEditor(mainData[0].editors, 'zposId', 'data', configSelectData(res[1], 'id', 'posname'));
						//赋值
						_that.$refs.autoform.configData = mainData;
						if(fileId){
							for(let item of _that.$refs.autoform.configData[0].editors){
								item.type = 'labelbox'
							}
							let fieldArr = getFormFields(mainData)
							fieldArr.push('id')
							for(let index in res[2].value.tinstMonthlyTargetIndex){
								if(fieldArr.includes(index)){
									_that.$refs.autoform.$set(_that.$refs.autoform.formdata,index,res[2].value.tinstMonthlyTargetIndex[index])
									_that.$set(_that.formdata,index,res[2].value.tinstMonthlyTargetIndex[index])
								}
							}
							var dataList = _that._.cloneDeep(res[2].value.tachievementIndex_data)
							_that.workList = dataList
							_that.$refs.autoform.$set(_that.$refs.autoform.formdata, "objStr1", JSON.stringify(dataList))
							_that.$set(_that.formdata, "objStr1", JSON.stringify(dataList))
							delete res[2].value.dataList
						}
					} else {
						_that.om.toast(res[0].msg);
					}
				})
				.catch(err => {
					console.log(err);
				});
		}
	},
	onLoad(options) {
		let _that = this;
		_that.menuName = options.title || '项目任务分配';
		uni.setNavigationBarTitle({
			title: _that.menuName
		});
		formShowLoading(_that)
		_that.busCode = options.code;
		_that.formdata.userId = this.userId;
		_that.initLoad(options);
		uni.removeStorage({
			key: _that.workCacheKey
		})
	},
	onShow() {
		let _that = this;
		if (_that.$refs.autoform) {
			uni.getStorage({
				key: _that.workCacheKey,
				success: function(res) {
					_that.workList = res.data;
					uni.removeStorage({
						key: _that.workCacheKey
					});
				}
			});
			uni.getStorage({
				key: _that.userCacheKey,
				success: function(res) {
					if(res.data){
						let d = res.data
						var formdata  = _that.$refs.autoform.formdata
						formdata.userId = d.id
						formdata.userName = d.username
						uni.removeStorage({
							key: _that.userCacheKey
						});
					}
				}
			});
		}
	}
};
</script>
<style></style>
